package com.syher.util.excel;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.syher.util.excel.node.HeaderNode;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class POIUtil {
    public static int generateHeader(List<HeaderNode> nodes, Sheet sheet, CellStyle style) {
        int dataStartRow = 0;
        Map<String, Integer> widthMap = Maps.newHashMapWithExpectedSize(nodes.size());
        for (HeaderNode node : nodes) {
            if (node.getFirstRow() != node.getLastRow() || node.getFirstCol() != node.getLastCol()) {
                CellRangeAddress cra = new CellRangeAddress(node.getFirstRow(), node.getLastRow(),
                        node.getFirstCol(), node.getLastCol());
                sheet.addMergedRegion(cra);
            }
            dataStartRow = dataStartRow >= node.getLastRow() ? dataStartRow : node.getLastRow();

            Row row = sheet.getRow(node.getFirstRow());
            if (null == row) {
                row = sheet.createRow(node.getFirstRow());
            }
            Cell cell = row.createCell(node.getFirstCol());
            cell.setCellValue(node.getValue());
            cell.setCellStyle(node.getStyle() == null ? style : node.getStyle());

            Integer width = widthMap.getOrDefault(String.valueOf(node.getFirstCol()), 0);
            widthMap.put(String.valueOf(node.getFirstCol()), getColumnWidth(node, width));
            sheet.setColumnWidth(node.getFirstCol(), widthMap.get(String.valueOf(node.getFirstCol())));
        }
        return dataStartRow + 1;
    }

    private static Integer getColumnWidth(HeaderNode node, Integer oldWidth) {
        String regex = "[\\u4e00-\\u9fa5]+";
        if (Strings.isNullOrEmpty(node.getValue())) {
            return oldWidth;
        }
        String name = node.getValue();
        Matcher matcher = Pattern.compile(regex).matcher(name);
        Integer width = 0;
        while (matcher.find()) {
            String chinese = matcher.group(0);
            width += chinese.length() * 512;
        }
        width += name.replaceAll(regex, "").length() * 256 + 512;
        return node.getFirstCol() != node.getLastCol() ? oldWidth : width > oldWidth ? width : oldWidth;
    }

/*    public static void main(String[] args) {

    }*/
}
